package com.firebird.app.reader.pdf.util

import android.annotation.SuppressLint
import android.text.TextUtils
import android.util.Log
import com.firebird.app.reader.pdf.bean.PDFFileInfo
import java.io.File
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*

object PDFUtil {
    /**
     * 读取文件的最后修改时间的方法
     */
    fun getFileLastModifiedTime(f: File): String {
        val cal = Calendar.getInstance()
        val time = f.lastModified()
        val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        cal.timeInMillis = time
        return formatter.format(cal.time)
    }

    fun getFileInfoFromFile(file: File): PDFFileInfo {
        val fileInfo = PDFFileInfo()
        fileInfo.setFileName(file.name)
        fileInfo.setFilePath(file.path)
        fileInfo.fileSize=file.length()
        //        fileInfo.setDirectory(file.isDirectory());
        fileInfo.setTime(getFileLastModifiedTime(file))
        val lastDotIndex = file.name.lastIndexOf(".")
        if (lastDotIndex > 0) {
            val fileSuffix = file.name.substring(lastDotIndex + 1)
            //            fileInfo.setSuffix(fileSuffix);
        }
        return fileInfo
    }

    fun FormetFileSize(fileS: Long): String {
        val df = DecimalFormat("#.00")
        var fileSizeString = ""
        val wrongSize = "0B"
        if (fileS == 0L) {
            return wrongSize
        }
        fileSizeString = if (fileS < 1024) {
            df.format(fileS.toDouble()) + "B"
        } else if (fileS < 1048576) {
            df.format(fileS.toDouble() / 1024) + "KB"
        } else if (fileS < 1073741824) {
            df.format(fileS.toDouble() / 1048576) + "MB"
        } else {
            df.format(fileS.toDouble() / 1073741824) + "GB"
        }
        return fileSizeString
    }

    /**
     * 利用文件url转换出文件名
     *
     * @param url
     * @return
     */
    fun parseName(url: String): String? {
        var fileName: String? = null
        try {
            fileName = url.substring(url.lastIndexOf("/") + 1)
        } finally {
            if (TextUtils.isEmpty(fileName)) {
                fileName = System.currentTimeMillis().toString()
            }
        }
        return fileName
    }

    /**
     * 将url进行encode，解决部分手机无法下载含有中文url的文件的问题（如OPPO R9）
     *
     * @param url
     * @return
     * @author xch
     */
    fun toUtf8String(url: String): String {
        val sb = StringBuffer()
        for (i in 0 until url.length) {
            val c = url[i]
            if (c.toInt() >= 0 && c.toInt() <= 255) {
                sb.append(c)
            } else {
                var b: ByteArray
                b = try {
                    c.toString().toByteArray(charset("utf-8"))
                } catch (ex: Exception) {
                    println(ex)
                    ByteArray(0)
                }
                for (j in b.indices) {
                    var k = b[j].toInt()
                    if (k < 0) k += 256
                    sb.append("%" + Integer.toHexString(k).toUpperCase())
                }
            }
        }
        return sb.toString()
    }

    fun parseFormat(fileName: String): String {
        return fileName.substring(fileName.lastIndexOf(".") + 1)
    }

    fun getFileType(paramString: String): String {
        var str = ""
        if (TextUtils.isEmpty(paramString)) {
            Log.d("print", "paramString---->null")
            return str
        }
        Log.d("print", "paramString:$paramString")
        val i = paramString.lastIndexOf('.')
        if (i <= -1) {
            Log.d("print", "i <= -1")
            return str
        }
        str = paramString.substring(i + 1)
        Log.d("print", "paramString.substring(i + 1)------>$str")
        return str
    }

    /**
     * 根据文件后缀名获得对应的MIME类型。
     */
    @SuppressLint("DefaultLocale")
    fun getMIMEType(file: File): String {
        var type = "*/*"
        val fName = file.name
        // 获取后缀名前的分隔符"."在fName中的位置。
        val dotIndex = fName.lastIndexOf(".")
        if (dotIndex < 0) {
            return type
        }
        /* 获取文件的后缀名 */
        val end = fName.substring(dotIndex, fName.length).toLowerCase()
        if (end === "") {
            return type
        }
        // 在MIME和文件类型的匹配表中找到对应的MIME类型。
        for (i in MIME_MapTable.indices) {
            if (end == MIME_MapTable[i][0]) {
                type = MIME_MapTable[i][1]
            }
        }
        return type
    }

    private val MIME_MapTable =
            arrayOf(
                    arrayOf(".3gp", "video/3gpp"),
                    arrayOf(".apk", "application/vnd.android.package-archive"),
                    arrayOf(".asf", "video/x-ms-asf"),
                    arrayOf(".avi", "video/x-msvideo"),
                    arrayOf(".bin", "application/octet-stream"),
                    arrayOf(".bmp", "image/bmp"),
                    arrayOf(".c", "text/plain"),
                    arrayOf(".class", "application/octet-stream"),
                    arrayOf(".conf", "text/plain"),
                    arrayOf(".cpp", "text/plain"),
                    arrayOf(".doc", "application/msword"),
                    arrayOf(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
                    arrayOf(".xls", "application/vnd.ms-excel"),
                    arrayOf(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
                    arrayOf(".exe", "application/octet-stream"),
                    arrayOf(".gif", "image/gif"),
                    arrayOf(".gtar", "application/x-gtar"),
                    arrayOf(".gz", "application/x-gzip"),
                    arrayOf(".h", "text/plain"),
                    arrayOf(".htm", "text/html"),
                    arrayOf(".html", "text/html"),
                    arrayOf(".jar", "application/java-archive"),
                    arrayOf(".java", "text/plain"),
                    arrayOf(".jpeg", "image/jpeg"),
                    arrayOf(".jpg", "image/jpeg"),
                    arrayOf(".js", "application/x-javascript"),
                    arrayOf(".log", "text/plain"),
                    arrayOf(".m3u", "audio/x-mpegurl"),
                    arrayOf(".m4a", "audio/mp4a-latm"),
                    arrayOf(".m4b", "audio/mp4a-latm"),
                    arrayOf(".m4p", "audio/mp4a-latm"),
                    arrayOf(".m4u", "video/vnd.mpegurl"),
                    arrayOf(".m4v", "video/x-m4v"),
                    arrayOf(".mov", "video/quicktime"),
                    arrayOf(".mp2", "audio/x-mpeg"),
                    arrayOf(".mp3", "audio/x-mpeg"),
                    arrayOf(".mp4", "video/mp4"),
                    arrayOf(".mpc", "application/vnd.mpohun.certificate"),
                    arrayOf(".mpe", "video/mpeg"),
                    arrayOf(".mpeg", "video/mpeg"),
                    arrayOf(".mpg", "video/mpeg"),
                    arrayOf(".mpg4", "video/mp4"),
                    arrayOf(".mpga", "audio/mpeg"),
                    arrayOf(".msg", "application/vnd.ms-outlook"),
                    arrayOf(".ogg", "audio/ogg"),
                    arrayOf(".pdf", "application/pdf"),
                    arrayOf(".png", "image/png"),
                    arrayOf(".pps", "application/vnd.ms-powerpoint"),
                    arrayOf(".ppt", "application/vnd.ms-powerpoint"),
                    arrayOf(".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"),
                    arrayOf(".prop", "text/plain"),
                    arrayOf(".rc", "text/plain"),
                    arrayOf(".rmvb", "audio/x-pn-realaudio"),
                    arrayOf(".rtf", "application/rtf"),
                    arrayOf(".sh", "text/plain"),
                    arrayOf(".tar", "application/x-tar"),
                    arrayOf(".tgz", "application/x-compressed"),
                    arrayOf(".txt", "text/plain"),
                    arrayOf(".wav", "audio/x-wav"),
                    arrayOf(".wma", "audio/x-ms-wma"),
                    arrayOf(".wmv", "audio/x-ms-wmv"),
                    arrayOf(".wps", "application/vnd.ms-works"),
                    arrayOf(".xml", "text/plain"),
                    arrayOf(".z", "application/x-compress"),
                    arrayOf(".zip", "application/x-zip-compressed"),
                    arrayOf("", "*/*")
            )
}